import axios from 'axios'
// 配置基准路径
const baseURL = 'http://localhost:8888/api/private/v1'
axios.defaults.baseURL = baseURL

// 设置拦截器加入登录得token，用localStorage来储存
// 用config写入token
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  var token = localStorage.getItem('mytoken')
  config.headers.Authorization = token
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

export const login = (params) => {
  return axios.post('login', params).then((res) => {
    return res.data
  })
}

// 注意：params一定要写对，如果不是返回参数显示错误
export const getAllUsersList = (params) => {
  return axios.get('users', {params: params}).then((res) => {
    return res.data
  })
}

// 添加用户
export const addUser = (params) => {
  return axios.post('users', params).then(res => {
    return res.data
  })
}

// 编辑用户
// 变量需要使用反引号加${}包裹着来传，例如：${parmans.id}
export const editUser = (params) => {
  return axios.put(`users/${params.id}`, params).then(res => {
    return res.data
  })
}

// 删除用户
export const delUser = (id) => {
  return axios.delete(`users/${id}`).then(res => {
    return res.data
  })
}

// 修改用户状态
export const changeUser = (params) => {
  return axios.put(`users/${params.id}/state/${params.mg_state}`).then(res => {
    return res.data
  })
}

// 获取角色列表
export const getUserPowerList = () => {
  return axios.get('roles').then(res => {
    return res.data
  })
}

// 分配用户角色
export const assignRoles = (params) => {
  return axios.put(`users/${params.id}/role`, {rid: params.rid}).then(res => {
    return res.data
  })
}

// 获得权限列表
export const getPowerList = (type) => {
  return axios.get(`rights/${type}`).then(res => {
    return res.data
  })
}

// 删除角色指定权限
export const deleteRolePower = (params) => {
  return axios.delete(`roles/${params.roleId}/rights/${params.rightId}`).then(res => {
    return res.data
  })
}

// 获取角色授权
export const grantRoleRight = (params) => {
  return axios.post(`roles/${params.roleId}/rights`, {rids: params.rids}).then(res => {
    return res.data
  })
}
